/************************************************************************

								Heroes IV
					  Copyright 2000, The 3DO Company

	------------------------------------------------------------------
  						 bitmap_layer.h

	$Header: /resource_editor/bitmap_layer.h $

	$NoKeywords: $

 ************************************************************************/
#include "precompiled.h"
#pragma warning( disable: 4786 )

#include "campaign_file.h"

#include <cassert>
#include <fstream>

#include "streambuf_operators.h"

//t_campaign_file class loads and saves raw 24bit bitmaps.

char const t_resource_traits<t_campaign_file>::prefix[] = "game_maps";

char const t_resource_traits<t_campaign_file>::extension[] = "h4c";

namespace {

	unsigned short			k_campaign_file_version  = 1;
	const unsigned int		k_arbitary_memblock_size = 10000;

};

// Constructors / Destructor
t_campaign_file::t_campaign_file() : m_file_data (new t_memory_buffer_counted(1))
{

}

t_campaign_file::~t_campaign_file()
{

}

// Member functions	
bool t_campaign_file::read( std::streambuf& buffer)
{	
	int version			= get<t_int32>( buffer );
	
	m_file_data->read( buffer );

	return true;
}

bool t_campaign_file::write( std::streambuf& buffer ) const
{
	put<t_int32>( buffer, k_campaign_file_version );

	m_file_data->write( buffer );

	return true;
}

t_memory_buffer_counted_ptr t_campaign_file::get_data_buffer()
{
	return m_file_data;
}

void t_campaign_file::load_campaign_file( std::string & campaign_file )
{
	if (campaign_file.empty() == true) 
		return;
	
	std::filebuf					file;
	
	if (file.open( campaign_file.c_str(), std::ios::in | std::ios::binary ) == 0)
		return;

	load_campaign_file(file);

	file.close();

	return;
}

void t_campaign_file::load_campaign_file( std::streambuf& buffer )
{
	m_file_data->clear_buffer();

	char temp_buffer[k_arbitary_memblock_size]= {0};

	int read_size			= k_arbitary_memblock_size;
	int current_retrived	= 0;
	
	m_file_data->resize_working_buffer( k_arbitary_memblock_size );
	
	while (1)
	{	
		current_retrived = buffer.sgetn(temp_buffer, read_size);
		m_file_data->sputn( temp_buffer, current_retrived );	
		
		//if we retrived less than asked for, that in indicative of an eof condition.
		if (current_retrived < read_size)
			break;
	}
	
	//to make it more efficient we merge all the samll buffers into one large one 
	//since this has to be done either here or in the game.

	m_file_data->merge_buffers_for_read();

	m_file_data->compact();

	return;
}

void t_campaign_file::save_campaign_file( std::streambuf& buffer ) const
{
	m_file_data->dump_memory(buffer);
	
	return;
}
